﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TestClientApp
{
    public partial class Form1 : Form
    {
        Socket s;
        IPAddress ipAddress;
        IPEndPoint Addr;

        public Form1()
        {
            InitializeComponent();

            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ipAddress = IPAddress.Parse("127.0.0.1"); //IP-адресс
            Addr = new IPEndPoint(ipAddress, 8383); ; //конечная точка(IP и порт)
            s.Connect(Addr); //Коннектимся к срверу

            Thread myThread = new Thread(this.listenThread);
            myThread.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string message = this.textBox1.Text;
            byte[] msg = GetBytes(message); //Конвертируем
            s.Send(msg); //Отправляем
        }

        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            s.Close(); //Закрываем сокет
        }

        public void listenThread()
        {
            while (true)
            {
                try
                {
                    byte[] msg = new byte[s.Available];
                    s.Receive(msg); //Принимаем МСГ
                    string message = Encoding.UTF8.GetString(msg);
                    message = message.Replace("\0\0", " ").Replace("\0", "");
                    if (message != "")
                    {
                        //Console.WriteLine("someOne sad: " + message); //Конвертируем и выводим
                        this.textBox2.Text += "\n" + "someOne say: " + message;
                    }
                }
                catch (Exception ex)
                {
                    //this.isAlive = false;
                    //Console.WriteLine("Server is DEAD: " + ex.Message);
                    this.textBox2.Text += "\n" + "Server dead: " + ex;
                    break;
                }
            }
        }
    }
}
